import { View, Image, Text } from "@tarojs/components"
import { TBar, TBlock, TPage } from "../../../shared/ui"
import topBg from '../../../theme/quotes/quote-top-bg.png'
import { addCommasToNumber, debounce, getFirstLetterUpperCase } from "../../../utils"
import { IconFont } from "../../../theme/index"
import * as Rest from '../../service'
import { useEffect, useRef, useState } from "react"
import { BtcItem } from "../../block"
import { useDidHide, useDidShow } from "@tarojs/taro"
import Taro from "@tarojs/taro"

const Main = () => {
  const [btcList, setBtcList] = useState<any[]>([])
  const [socketTask, setSocketTask] = useState<any>()
  const [timer, setTimer] = useState<any>()

  const prevBtcListRef = useRef<any[]>([]);


  const [show, setShow] = useState(true)
  useDidShow(() => {
    setShow(() => { return true })
  })
  useDidHide(() => {
    console.log('hide')
    setShow(() => { return false })
  })

  const getBtcInfo = async () => {
    const res = await Rest.requestBtcListInfo()
    const { data = [] } = res
    setBtcList(data)
    prevBtcListRef.current = data;
  }


  useEffect(() => { getBtcInfo() }, [])


  useEffect(() => {
    timer && clearTimeout(timer)
    prevBtcListRef.current = btcList;
  }, [btcList])

  const updateInfo = (data) => {
    if (!data) return


    setBtcList((currentBtcList) => {
      console.log(currentBtcList);
      const itemExists = currentBtcList.some(item => item.S === data.S);
      if (!itemExists) return currentBtcList;
      return currentBtcList.map(item => {
        if (item.S === data.S) {
          return data;
        } else {
          return item;
        }
      });
    });
  }

  useDidShow(async () => {
    const socketTask = Taro.connectSocket({
      url: 'ws://47.96.138.184:8282'
    })
    setSocketTask(socketTask)
      ; (await socketTask).onMessage(callback => {
        const { data } = JSON.parse(callback.data)
        updateInfo(data)
      })
  })


  // 关闭socket
  useDidHide(async () => {
    ; (await socketTask).close(callback => {

    })
  })

  return show && <TPage>
    <TBar title={'行情'} />

    <TBlock>
      <View className="w-full h-[162px] bg-contain px-[24px] pt-[24px] py-[12px] mt-[20px] flex flex-col justify-between" style={{ background: `url(${topBg})`, backgroundSize: '100% 100%' }}>
        <View className="w-full h-[50px] flex justify-between items-center">
          <View className='text-[36px] text-[#0287F7]'>USDT</View>
          <View className="flex items-center">
            <View className="text-[24px] text-[#ffffff]">余额：</View>
            <View>{`$${addCommasToNumber(5230.25)}`}</View>
            <View className="px-[8px]">
              <IconFont name='refresh' size={40} color='#0287F7' />
            </View>
          </View>
        </View>
        <View className="w-full h-[50px] flex justify-between items-center">
          <View className='text-[28px] text-[#ffffff] flex items-center'>
            <View className="px-[8px] ">
              <IconFont name='today' size={40} color='#ffffff' />
            </View>
            <View>今日输赢</View>
          </View>
          <View className="flex items-center">
            <View>{`$${addCommasToNumber(5230.25)}`}</View>
          </View>
        </View>
      </View>
    </TBlock>
    <TBlock>
      <View className="w-full h-[68px] bg-[#191933] rounded-[8px] mt-[20px] px-[16px] flex items-center">
        <View className="px-[8px] ">
          <IconFont name='tanhao' size={28} color='#ffffff' />
        </View>
        <View className="flex-1 text-[24px] text-[#ffffff] truncate text-ellipsis">
          输赢操作只能使用USDT币种,如果币种余额不足,请转换
        </View>
        <View className="px-[8px] ">
          <IconFont name='transform' size={28} color='#ffffff' />
        </View>
      </View>
    </TBlock>

    <TBlock classNames="mt-[10px]">
      {
        btcList.map((item, index) => {
          return (
            <BtcItem item={item} prev={prevBtcListRef.current[index]} key={index} />
          )
        })
      }
    </TBlock>
  </TPage>
}

export default Main
